var oilPriceManageData = [];
var deleteFlag = undefined;
var index = undefined;
var oilChartData = [];
var maxOilPrice = undefined;
var minOilPrice = undefined;

$(document).ready(function() {
	showLoading();
	$('title', parent.document).html($('title').text());
	createTableHead("oilPriceManageThead", oilPriceManageTable);
	setBaseUrl();
	search();
});
function search(){
	$ajax('searchOilPriceManage', 'oilPriceManageSearch', searchOilPriceManage);
}
function searchOilPriceManage(data){
	oilPriceManageData = data && data.oilPriceManageList || [];
	var length = oilPriceManageData.length;
	createTableBody("oilPriceManageTbody", oilPriceManageTable, oilPriceManageData, false, true);
	if(length > 0){
		maxOilPrice = oilPriceManageData[0].maxOilPrice;
		minOilPrice = oilPriceManageData[0].minOilPrice;
		if(oilPriceManageData.length == 1){
			$("#details0").attr("hidden", true);
		}
		oilChartData = [];
		for (var i = 0; i < length; i++) {
			$('#servicePrice' + i).html((oilPriceManageData[i].oilPrice * oilPriceManageData[i].servicePriceRate).toFixed(4));
			if(oilPriceManageData[i].voucherImageLength > 0){
				$('#voucherImagePath' + i).html('<img src="static/images/fileExistPdf.png" title="下载" style="width:25px;height:25px;cursor: pointer;" onclick="exportFile(' + i + ')" />' + formatFileSize(oilPriceManageData[i] && oilPriceManageData[i].voucherImageLength));
			} else {
				$('#voucherImagePath' + i).html('<img src="static/images/fileNotExistPdf.png" title="上传" onclick="upLoadFile(' + i + ')" style="width:25px;height:25px;cursor: pointer;" />');
			}
			oilChartData.push([
			                   stringToDate(date2String(oilPriceManageData[i].oilEffectiveDTTM)),
			                   oilPriceManageData[i].oilPrice
			               ]);
		}
		changeEchart();
	}
}
function exportFile(index){
	deleteFlag = "export";
	showMessge("确定下载吗?", "model2");
	url = 'getVoucherImg?oilEffectiveDate=' + date2String(oilPriceManageData[index].oilEffectiveDTTM) + '&&checkFlag=';
}
function exportFileResult(data){
	var result = data && data.result;
	if (result == "Success") {
		downloadFile(url + "OK");
		showMessge("下载成功！");
	} else if (result == "NotFound") {
		showMessge("下载失败，下载文件不存在！");
	} else {
		showMessge("下载失败，请重新下载！");
	}
}
function upLoadFile(index){
	deleteFlag = "import";
	$("#importFileForm").empty();
	$("#importFileForm").append('<input name="oilEffectiveDate" type="text" value="' + date2String(oilPriceManageData[index].oilEffectiveDTTM) + '" hidden/>');
	$("#importFileForm").append(
		'<div class="form-group" >'+
		'<label for="importFile" class="col-sm-3 control-label">油价凭证文件</label>' + 
		'<div class="col-sm-8"><input id="importFile" name="importFile" type="file" class="form-control"/></div>' + 
		'</div>'
	);
	var option = {
		allowedFileExtensions: ['pdf'],
		showUpload: false,
		showErrorPreview: false,
		previewFileIcon: '<img src="static/images/pdf.png" style="width:80px;height:80px;" />'
	};
	selectFile("importFile", option);
	$("#fileinputModal").modal("show");
	$("#uploadBtn").attr('disabled', false);
	$("#uploadCancelBtn").attr('disabled', false);
}
function save(index){
	createComBody("detailOneBody", oilPriceManageTable, oilPriceManageData[index], 1);
	deleteFlag = "save";
	$ajaxList('searchBalanceInitSetting', getBalanceInitSetting);
	$("#save").modal('show');
	$("#saveBtn").attr('disabled', false);
	$("#saveCancelBtn").attr('disabled', false);
	selectDate("oilEffectiveDate1");
	option = {
			uploadUrl : "saveOilPriceManage",
			allowedFileExtensions : ['pdf'],//接收的文件后缀
			showUpload: false, //是否显示上传按钮
		    showCaption: false,//是否显示标题
		    previewFileIcon: '<img src="static/images/pdf.png" style="width:60px;height:60px;" />',
		    showErrorPreview: false
	}
	selectFile("uploadFile", option);
	$("#addMessage").children()[0].style.width = '100%';
}
function getBalanceInitSetting(data){
	var balanceInitSettingData = data.balanceInitSettingList[0]
	$("#servicePriceRate").val(balanceInitSettingData.defaultServicePriceRate);
}
function saveInfo(){
	if (!checkForm("saveForm", oilPriceManageTable)) return;
	if(checkNum("oilPrice") && checkNum("servicePriceRate", 2)){
		if($("#uploadFile").get(0).files.length != 0){
			$("#saveBtn").attr('disabled', 'disabled');
			$("#saveCancelBtn").attr('disabled', 'disabled');
			showLoading();
			$ajaxSubmit("saveForm", "saveOilPriceManage", saveOilPriceManage);
		} else {
			showMessge("请选择油价凭证文件");
		}
	}
}
function saveOilPriceManage(data){
	if(deleteFlag == "save"){
		var result = data && data.result;
		if (result == "Success") {
			setTimeout(hideLoading, 500);
			showMessge(messageContent["Insert.Success"]);
			$('#save').modal('hide');
			formReset("saveForm");
		} else if (result == "OilEffectiveDTTMNoNull"){
			showMessge("生效时间已存在！");
		} else if (result == "NotFound"){
			showMessge(messageContent["Insert.Failed"]);
		} else if (result == "NotFoundFile") {
			showMessge("添加失败，文件不存在");
		} else {
			showMessge(messageContent["Insert.Error"]);
		}
		$("#saveBtn").attr('disabled', false);
		$("#saveCancelBtn").attr('disabled', false);
	}
	search();
}
function confirm(){
	if(deleteFlag == "save"){
		return checkForm("saveForm", oilPriceManageTable);
	} else if(deleteFlag == "import"){
		var importFile = $("#importFile").val();
		if (!importFile) {
			$("#importFile").tips({
				side : 2,
				msg : '请选择油价凭证文件',
				bg : '#AE81FF',
				time : 3
			});
			$("#importFile").focus();
		} else {
			$("#uploadBtn").attr('disabled', 'disabled');
			$("#uploadCancelBtn").attr('disabled', 'disabled');
			showLoading();
			$ajaxSubmit('importFileForm', 'importOilImage', importFileResult);
		}
	}
}
function importFileResult(data) {
	setTimeout(hideLoading, 500);
	var result = data && data.result;
	if (result == "Success") {
		$("#fileinputModal").modal("hide");
		showMessge("上传成功！");
		search();
	} else if (result == "NotFound") {
		showMessge("上传失败，文件不存在!");
	} else {
		showMessge("上传异常，请重新选择油价凭证文件 或 联系管理员！");
	}
	$("#uploadBtn").attr('disabled', false);
	$("#uploadCancelBtn").attr('disabled', false);
}
function getUrl(){
	if(deleteFlag == "save"){
		return 'saveOilPriceManage';
	} else if(deleteFlag == "delete"){
		return 'deleteOilPriceManage';
	}
}
function chkBefore(i, chkFlag){
	showMessge(messageContent["Delete.Confirm"], "model2");
	saveFlag = "delete";
	deleteFlag = "delete";
	index = i;
}
function getData(){
	return {oilEffectiveDate: timeStamp2String(oilPriceManageData[index].oilEffectiveDTTM)};
}
function sure(data){
	if(deleteFlag == "delete"){
		var result = data && data.result;
	    if (result == "Success") {
			showMessge(messageContent["Delete.Success"]);
		} else if (result == "NotFound") {
			showMessge(messageContent["Delete.NotFound"]);
		} else {
			showMessge(messageContent["Delete.Error"]);
		}
	    search();
	} else if (deleteFlag == "export"){
		showMessge("下载中......");
		$ajax(url, undefined, exportFileResult);
	}
}
function changeEchart(){
	$("#histogram").empty();
	if(oilPriceManageData.length == 0){
		$("#contenter").attr("hidden",true);
		return;
	}
	$("#contenter").attr("hidden",false);
	myChart = echarts.init(document.getElementById('histogram'));
	var theadName = "油价(元)";
    var option = {
            tooltip : {
            	trigger: 'axis',
            	axisPointer:{
            		label: {
            			formatter: function (params) {
            				if (params && params.value) {
            					return date2String(new Date(params.value)).substr(0, 7);
            				} else {
            					'时间异常';
            				}
            			}
            		}
            	}
            },
            xAxis: [
                {
                	type: 'time',
                	name: '日期',
                	splitNumber: 12,
                	min: getSystemTime().getFullYear() + '-' + "01",
                	max: getSystemTime().getFullYear() + '-' + "12",
                	axisLabel: {
                		formatter : function (effectiveTime) {
                			if(effectiveTime){
                				return date2String(new Date(effectiveTime)).substr(0, 7);
                			} else {
                				return '';
                			}
                        }
                	}
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    name: theadName,
                    min: minOilPrice && minOilPrice < 4 ? minOilPrice : 4,
		    max: maxOilPrice && maxOilPrice > 7 ? maxOilPrice :  7,
                }
            ],
            series: [
                {
                    name:theadName,
                    type:'line',
                    barWidth:3,
                    itemStyle: {
                        normal : {
                            color: '#09be09',
                        }
                    },
                    data: oilChartData
                }
            ]
        };
    myChart.setOption(option);
}